﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using CardInChina.Data.Entity.Entity;

namespace CardInChina.Data.Entity.Interface
{
    public class CustomerService
    {
        private CICEntities _db = new CICEntities();
        private SysVerifyService svs = new SysVerifyService();

        public Customer Login(string account, string password)
        {
            if (string.IsNullOrEmpty(account))
                throw new ArgumentNullException("account");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");

            // always convert alias or email to lower case
            account = account.ToLower();

            using (CICEntities db = new CICEntities())
            {
                var sql = db.Customers.Where(c => (c.Account == account || c.Email == account)
                    && c.Password == MySqlFunctions.OldPassword(password));

                return sql.FirstOrDefault();

                // TODO: 登陆的IP和常用IP的国家不同
            }
        }

        public Customer GetCustomerByCustomerID(int customerID)
        {
            //using (CICEntities db = new CICEntities())
            //{
            var customer = _db.Customers.FirstOrDefault(c => c.CustomerID == customerID);
            return customer;
            //}
        }



        public Customer Register(string email, string alias, string password, string referer, int? recommended, string ipAddress)
        {
            if (string.IsNullOrEmpty(email))
                throw new ArgumentNullException("email");
            if (string.IsNullOrEmpty(alias))
                throw new ArgumentNullException("alias");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");

            using (CICEntities db = new CICEntities())
            {
                if (db.Customers.FirstOrDefault(p => p.Account == alias || p.Email == email) != null)
                    throw new ApplicationException("帐号或邮箱已经存在，注册失败");

                var customer = new Customer()
                {
                    Account = alias,
                    Email = email,
                    Password = MySqlFunctions.OldPassword(password),

                    MacID = "00-00-00-00-00-00",
                    RegisterDate = DateTime.UtcNow,
                    LastLogonDate = DateTime.UtcNow,

                    Recommended = recommended,
                    Referer = referer,
                    IP = ipAddress,
                    //IPCountry = "",

                    //VerifyCode = "",
                    //VerifyMethod = "",
                };

                db.Customers.Add(customer);

                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    // TODO:
                    throw;
                }

                // VerifyCode旨在验证Balance(余额)是否被篡改
                customer.Balance = 0;
                customer.VerifyCode = customer.GenerateVerifyCode();


                //TODO: 黑名单鉴别
                //sql_black="select * from blacklist where blacklist_value='"&ip&"' or blacklist_value='"&email&"' or blacklist_value='"&phone&"' or blacklist_value='"&customer_name&"' or blacklist_value='"&mac_id&"' "	
                //Set rs_black=conn.execute(sql_black)
                //If Not rs_black.eof Then
                //    sql=sql&",cust_memo='与黑名单中记录 有关联!blacklist_id="&rs_black("blacklist_id")&"'"
                //End If
                //sql=sql&" where cust_id="&cust_id
                //conn.execute sql


                //TODO: 发送认证邮件
                //var v = new SysVerify
                //{
                //    Code = Guid.NewGuid().ToString(),
                //    ExpireAfter = 7 * 24 * 3600, // 7天
                //    ForId = customer.CustomerID,
                //};
                //db.SysVerifies.Add(v);
                svs.CreateOne(customer.CustomerID, 7 * 24 * 3600); // 7天

                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    // TODO:
                    throw;
                }

                return customer;
            }
        }

        public Customer SetEmailVerified(int cid)
        {
            using (CICEntities db = new CICEntities())
            {
                var cc = db.Customers.Single(p => p.CustomerID == cid);
                cc.EmailConfirmed = true;
                db.SaveChanges();
                return cc;
            }
        }
    }
}
